package com.cskaoyan.wordmemorize.controller.admin;


import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.common.util.IpUtil;
import com.cskaoyan.wordmemorize.dto.admin.AdminLoginDTO;
import com.cskaoyan.wordmemorize.dto.admin.EmployeeDTO;
import com.cskaoyan.wordmemorize.request.EmployeeLoginRequest;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("admin")
public class AdminLoginController {


    @Resource
    EmployeeService employeeService;

    @PostMapping("login")
    public Result<AdminLoginDTO> login(@RequestBody EmployeeLoginRequest loginRequest, HttpServletRequest request) {
        // 匹配用户登录时输入的用户名和密码
        EmployeeDTO employee = employeeService.login(loginRequest.getUsername(),loginRequest.getPassword());

        // 登录成功，开启用户的account-session
        String idStr = employee.getId();
        long id = Long.parseLong(idStr);
        StpKit.ADMIN.login(id);

        String ipAddr = IpUtil.getIpAddr(request);

        // 登录成功后，更新用户的登录信息
        employeeService.updateLoginInfo(id,ipAddr,LocalDateTime.now());

        // 获取用户的account-session对应的token
        String tokenValue = StpKit.ADMIN.getTokenValue();
        AdminLoginDTO adminLoginDTO = new AdminLoginDTO();
        adminLoginDTO.setToken(tokenValue);

        return Result.ok(adminLoginDTO);

    }
    @PutMapping("logout")
    public Result logout(){
        // 1. 检查当前是否有用户登录
        if (!StpKit.ADMIN.isLogin()) {
            return Result.fail("未登录，无需退出");
        }

        // 2. 获取当前用户信息（用于日志或审计）
        long userId = StpKit.ADMIN.getLoginIdAsLong();

        // 3. 执行退出操作
        StpKit.ADMIN.logout();

        // 4. 返回明确结果
        return Result.ok("退出成功");
    }
}
